import 'dart:io';
import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:flutter_foreground_service/flutter_foreground_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tts_server/server.dart';
import 'package:tts_server/tts.dart';
import 'package:wakelock_plus/wakelock_plus.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter TTS Server',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter TTS Server'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String recvData = '';
  double speed = 1.0;
  String localAddr = '';

  Future<void> startServer() async {
    ReceivePort recv = ReceivePort();
    myServer(9800, recv.sendPort);
    recv.listen((message) async {
      if (message is String) {
        setState(() {
          recvData = message;
          _counter++;
        });
        if (GlobalData.play) {
          //print('fhz:speak: $message');
          await flutterTts.speak(message);
        }
      }
    });
  }

  Future<String> getIps() async {
    String ret = "";
    for (var interface in await NetworkInterface.list()) {
      ret = '$ret== Interface: ${interface.name} ==\n';
      for (var addr in interface.addresses) {
        if(!addr.isLoopback) {
          ret =
            '$ret${addr.address} ${addr.host} ${addr.type.name}\n';
        }
      }
    }
    return ret;
  }

  @override
  void initState() {
    SharedPreferences.getInstance().then((store) {
      speed = store.getDouble('speed') ?? speed;
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      ForegroundService().start();
      await ForegroundServiceHandler.stopForegroundService();
      await ForegroundServiceHandler.notification.setTitle('TTS Server');
      await ForegroundServiceHandler.notification.setText('Running');
      //await ForegroundServiceHandler.getWakeLock();
      await ForegroundServiceHandler.setContinueRunningAfterAppKilled(false);
      //await ForegroundServiceHandler.setServiceIntervalSeconds(10);
      //await ForegroundServiceHandler.setServiceFunction(serviceCallback);
      await ForegroundServiceHandler.startForegroundService(null, true);
      WakelockPlus.enable();
      localAddr = await getIps();
      setState(() {});
    });
    super.initState();
    WidgetsFlutterBinding.ensureInitialized();
    startServer();
    ttsInit().then((value) {
      setState(() {});
    });
  }

  @override
  void dispose() {
    ForegroundServiceHandler.stopForegroundService().then((value) {
      ForegroundService().stop();
      WakelockPlus.disable();
    });

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Text('语音引擎：${GlobalData.ttsEngine}'),
          Text('本机IP：\n$localAddr'),
          GestureDetector(
            child: Image.asset("images/speaker.jpg",width: 200,height: 200,),
            onTap: () {
              setState(() {
                GlobalData.play = !GlobalData.play;
              });
            },
          ),
          Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text('是否播放语音？'),
                Checkbox(
                  value: GlobalData.play,
                  onChanged: (b) {
                    setState(() {
                      GlobalData.play = b!;
                    });
                  },
                  semanticLabel: '播放语音？',
                ),
              ],
            ),
          ),
          Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('语速:${speed.toStringAsFixed(2)}'),
                Slider(
                  value: speed,
                  onChanged: (val) async {
                    var store = await SharedPreferences.getInstance();
                    store.setDouble('speed', val);
                    flutterTts.setSpeechRate(val);
                    if (mounted) {
                      setState(() {
                        speed = val;
                      });
                    }
                  },
                  min: 0.1,
                  max: 1.7,
                  label: '语速${speed.toStringAsFixed(2)}',
                ),
              ],
            ),
          ),
          const Text(
            '请求次数:',
          ),
          Text(
            '$_counter',
            style: Theme.of(context).textTheme.headlineMedium,
          ),
          Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text('是否显示文字？'),
                Checkbox(
                  value: GlobalData.showText,
                  onChanged: (b) {
                    setState(() {
                      GlobalData.showText = b!;
                    });
                  },
                  semanticLabel: '显示文字？',
                ),
              ],
            ),
          ),
          GlobalData.showText ? Text(recvData) : const Text(''),
        ],
      ),
    );
  }
}

@pragma('vm:entry-point')
Future<void> serviceCallback() async {
  print('wake up');
}
